﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using SBS.Common;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;
//using System.ServiceModel.Dispatcher;


namespace SBS.Common
{
   /// <summary>
   /// C# Object 基础类库扩展
   /// </summary>   
    public static class ObjectExtension
    {
        /// <summary>
        /// 内部使用 XmlSerializer 序列化当前对象，用于对象持久化或传输。
        /// 该方法位于 SBS.Common.dll
        /// </summary>
        /// <param name="obj"></param>
        /// <returns>默认生成 Encoding.ASCII 编码的 Xml 字符串。</returns>
        public static string SerializeToString(this object obj)
        {
            return obj.SerializeToString(Encoding.ASCII);
        }

        /// <summary>
        /// 内部使用 XmlSerializer 序列化当前对象，用于对象持久化或传输。
        /// 该方法位于 SBS.Common.dll
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="Encoding">指定生成字符串的编码</param>
        /// <returns></returns>
        public static string SerializeToString(this object obj, Encoding Encoding)
        {            
            XmlSerializer Serializer = new XmlSerializer(obj.GetType());
            MemoryStream stream = new MemoryStream();
            Serializer.Serialize(stream, obj);
            byte[] buf = stream.ToArray();
            string xml = Encoding.GetString(buf);
            stream.Close();            
            return xml;
        }

        /// <summary>
        /// 内部使用 DataContractSerializer 序列化当前对象，用于对象持久化或传输。
        /// 该方法位于 SBS.Common.dll
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="Encoding">指定生成字符串的编码</param>
        /// <returns></returns>
        public static string SerializeDataToString(this object obj, Encoding Encoding)
        {
            DataContractSerializer Serializer = new DataContractSerializer(obj.GetType());
            MemoryStream ms = new MemoryStream();
            Serializer.WriteObject(ms, obj);
            byte[] buf = ms.ToArray();
            return Encoding.GetString(ms.ToArray());
        }
        /// <summary>
        /// 内部使用 DataContractSerializer 序列化当前对象，用于对象持久化或传输。
        /// 该方法位于 SBS.Common.dll
        /// </summary>
        /// <param name="obj"></param>
        /// <returns>默认生成 Encoding.ASCII 编码的字符串。</returns>
        public static string SerializeDataToString(this object obj)
        {
            return obj.SerializeDataToString(Encoding.ASCII);
        }
        
    }
   
}
